<?php 
global $_GPC, $_W;
$cfg = $this->module['config'];
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';

if($operation=="login"){
    $userid=$_GPC["userid"];
    $pwd=$_GPC["pwd"];
    $mei=$_GPC["mei"];
    if(!$userid || !$pwd || !$mei)die($_GET['callback']."(".json_encode(array("success"=>false,"msg"=>"用户名或者密码错误")).")");
    $pwd=md5($_GPC['pwd']);
    $item=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_user')." WHERE weid='{$_W['uniacid']}' and useracount=:a and password=:b limit 1",array(":a"=>$userid,":b"=>$pwd));
    if(!$item)die($_GET['callback']."(".json_encode(array("success"=>false,"msg"=>"用户不存在或者密码错误")).")");
    if(!$item['status'])die($_GET['callback']."(".json_encode(array("success"=>false,"msg"=>"该用户还没有审核，请联系管理员")).")");
    if(!$item['isimei'] && !$item['imei']){
        pdo_update("j_hmoney_user",array("imei"=>$mei),array("id"=>$item['id']));
        die($_GET['callback']."(".json_encode(array("success"=>false,"msg"=>"资料已提交，请等待管理员审核")).")");
    }
    if(!$item['imei'] || $item['imei']!=$mei)die($_GET['callback']."(".json_encode(array("success"=>false,"msg"=>"登陆设备错误")).")");
    if(!$item['isimei'])die($_GET['callback']."(".json_encode(array("success"=>false,"msg"=>"资料审核中")).")");
    $tokentime=TIMESTAMP;
    pdo_update("j_hmoney_user",array("tokentime"=>$tokentime),array("id"=>$item['id']));
    die($_GET['callback']."(".json_encode(array("success"=>true,"islogin"=>$item['id'],"user"=>$item,"floder"=>$cfg['floder'],"token"=>$tokentime)).")");
}

$userid=$_GPC["islogin"];
$mei=$_GPC["mei"];
if(!$userid)die($_GET['callback']."(".json_encode(array("success"=>false,"msg"=>"请先登陆")).")");
$user=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_user')." WHERE weid='{$_W['uniacid']}' and id=:a ",array(":a"=>$userid));
if(!$user)die($_GET['callback']."(".json_encode(array("success"=>false,"msg"=>"请先登陆")).")");
if(!$user['status'])die($_GET['callback']."(".json_encode(array("success"=>false,"msg"=>"该用户还没有审核，请联系管理员")).")");
#if(!$user['imei'] || $user['imei']!=$mei)die($_GET['callback']."(".json_encode(array("success"=>false,"msg"=>"登陆设备错误")).")");
$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE weid='{$_W['uniacid']}' and id=:a ",array(":a"=>$user['pcate']));
$shopid=$shop["id"];

if ($operation == 'gettablepcate') {
    $tablepcatelist = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_tablecategory') . " WHERE weid = '".$_W['uniacid']."' and groupid =:a order by displayorder asc,id desc",array(":a"=>$shopid));
    echo $_GET['callback']."(".json_encode(array('success'=>true,"list"=>$tablepcatelist)).")";
    die();
}elseif ($operation == 'gettablelist') {
    $pcate=$_GPC["pcate"];
    $tablelist = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_table') . " WHERE weid = '".$_W['uniacid']."' and pcate =:a order by displayorder asc,id desc",array(":a"=>$pcate));
    echo $_GET['callback']."(".json_encode(array('success'=>true,"list"=>$tablelist)).")";
    die();
}elseif ($operation == 'getorderdietal') {
    $tid=intval($_GPC['tid']);
    $person=intval($_GPC['person']);
    $orderid=intval($_GPC['orderid']);
    if(!$tid)die($_GET['callback']."(".json_encode(array("success"=>false,'msg'=>'请选择餐桌')).")");
    $table = pdo_fetch("SELECT * FROM ".tablename('j_hmoney_table')." WHERE id=:a ",array(":a"=>$tid));
    if($table['status']==0){
        $hasOldorder=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and tabile=:a and ispay=0 ",array(":a"=>$trade["tableid"]));
        if($hasOldorder)die($_GET['callback']."(".json_encode(array('success'=>false,'msg'=>"该餐桌还有订单未处理，请先处理该订单")).")");

        $orderDisplayorder=pdo_fetchcolumn("SELECT max(CONVERT(serialnum,SIGNED)) FROM " . tablename('j_hmoney_order') . " WHERE weid='".$_W['uniacid']."' and groupid=:a and createdate=:b ",array(":a"=>$shopid,":b"=>date("Y-m-d")));
        $data=array(
            "weid"=>$_W['uniacid'],
            "groupid"=>$shopid,
            "userid"=>$userid,
            "serialnum"=>$orderDisplayorder+1,
            "out_trade_no"=>TIMESTAMP.mt_rand(100,999),
            "tableid"=>$tid,
            "person"=>$person,
            "teafee"=>intval(($person*$table['perperson']+$table['teafee'])*100),
            "createtime"=>TIMESTAMP,
            "createdate"=>date("Y-m-d"),
            "createterminal"=>1,
        );
        pdo_insert("j_hmoney_order",$data);
        $orderid=pdo_insertid();
        pdo_update('j_hmoney_table',array("status"=>1,"orderid"=>$orderid,"createtime"=>TIMESTAMP),array("id"=>$tid));
        $table = pdo_fetch("SELECT * FROM ".tablename('j_hmoney_table')." WHERE id=:a ",array(":a"=>$tid));

        $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
        $this->wildDog_socket($shopid);
        echo $_GET['callback']."(".json_encode(array('success'=>true,'table'=>$table,'trade'=>$trade)).")";
        die();
    }elseif($table['status']==1){
        $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and tableid=:a and status<2 order by id desc limit 1",array(":a"=>$tid));
        if($orderid)$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
        $goodlist=pdo_fetchall("SELECT a.*,b.title,b.memberprice,b.unitname,b.marketprice,b.pcate FROM ".tablename('j_hmoney_ordergoods')." as a LEFT JOIN ".tablename('j_hmoney_goods')." as b ON a.goodid=b.id  WHERE a.out_trade_no=:a order by a.id desc ",array(":a"=>$trade['out_trade_no']));
        echo $_GET['callback']."(".json_encode(array('success'=>true,'table'=>$table,'trade'=>$trade,'goods'=>$goodlist)).")";
        die();
    }elseif($table['status']==2){
        $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and tableid=:a and status<2 order by id desc limit 1",array(":a"=>$tid));
        $goodlist=pdo_fetchall("SELECT a.*,b.title,b.memberprice,b.unitname,b.marketprice,b.pcate FROM ".tablename('j_hmoney_ordergoods')." as a LEFT JOIN ".tablename('j_hmoney_goods')." as b ON a.goodid=b.id  WHERE a.out_trade_no=:a order by a.id desc ",array(":a"=>$trade['out_trade_no']));
        die($_GET['callback']."(".json_encode(array('success'=>true,'table'=>$table,'trade'=>$trade,'goods'=>$goodlist)).")");
    }
    echo $_GET['callback']."(".json_encode(array("success"=>true)).")";
    die();

}elseif ($operation == 'getgoodpcate') {
    $goodpcatelist = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodcategory') . " WHERE weid = '".$_W['uniacid']."' and groupid =:a and status=1 order by  displayorder asc, id desc",array(":a"=>$shopid));
    die($_GET['callback']."(".json_encode(array("success"=>true,"list"=>$goodpcatelist)).")");

}elseif ($operation == 'getgoodlist') {
    $pcate=intval($_GPC['pcate']);
    $goodslist=array();
    if($pcate==-1){
        $list=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_goodmarket') . " WHERE groupid=:a and status=1 and starttime<=:b and endtime>=:b and contentid<>'' order by id desc",array(":a"=>$shopid,":b"=>TIMESTAMP));
        foreach($list as $row){
            if($row['limitweek']){
                $day=date('w') ? date('w') : 7;
                if(!in_array($day,explode(',',$row['limitweek'])))continue;
            }
            if($row['limithour']){
                $time=intval(date('h'));
                if(!in_array($time,explode(',',$row['limithour'])))continue;
            }
            $goods=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_goods')." WHERE id in(".$row['contentid'].") and status=1 and store<>0 order by id desc");
            for($i=0;$i<count($goods);$i++){
                $temp=$goods[$i];
                if(strpos($row['discount'],"%")){
                    $temp['title2']=(str_replace("%","",$row['discount'])*0.1)."折";
                    $temp['marketprice']=$this->_2money($goods[$i]['marketprice']*(str_replace("%","",$row['discount'])));
                }
                if(strpos($row['discount'],"-")!==false){
                    if($goods[$i]['marketprice']-abs($row['discount'])>=0){
                        $temp['title2']=(str_replace("-","立减",$row['discount']));
                        $temp['marketprice']=$this->_2money(($goods[$i]['marketprice']-abs($row['discount']))*100);
                    }

                }
                array_push($goodslist,$temp);
            }
        }
    }elseif($pcate==-2){
        $goodslist = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodpackage') . " WHERE groupid=:a and status=1 order by displayorder asc,id asc", array(":a" => $shopid));
    }else{
        $goodslist=pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goods') . " WHERE weid = '".$_W['uniacid']."' and pcate=:a and groupid=:b and status=1 and store<>0 order by displayorder asc,id asc",array(":a"=>$pcate,":b"=>$shopid));
    }
    for($i=0;$i<count($goodslist);$i++){
        if(!$goodslist[$i]['thumb'])continue;
        $goodslist[$i]['thumb']=tomedia($goodslist[$i]['thumb']);
    }
    die($_GET['callback']."(".json_encode(array('success'=>true,'list'=>$goodslist,"a"=>count($goods))).")");

}elseif ($operation == 'updateordergoods') {
    $orderid=$_GPC["orderid"];
    $param=$_GPC["orderary"];
    if(!$orderid)die($_GET['callback']."(".json_encode(array('success'=>false,'msg'=>"订单编号不能为空")).")");
    $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
    if($trade["ispay"])die($_GET['callback']."(".json_encode(array('success'=>false,'msg'=>"订单已付款")).")");
    $table=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_table')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$trade['tableid']));
    $sqlinsert="insert into ".tablename('j_hmoney_ordergoods')." (weid,groupid,orderid,out_trade_no,createtime,status,goodid,title,goodsn,num,price,oldprice,total_fee,ispack,taste)VALUES";
    $newgoodAry=array();
    $tempInsertAry=array();
    $isallnew=true;
    $param=explode("|**|",$param);
    foreach($param as $row){
        //oid + "|*|" + gid + "|*|" + title + "|*|" + goodsn + "|*|" + num + "|*|" + price + "|*|" + oprice + "|*|" + mprice + "|*|" + taste + "|*|" + fee
        $tempAry=explode("|*|",$row);
        if(!$tempAry[0]){
            if(!isset($newgoodAry[$tempAry[1]]))$newgoodAry[$tempAry[1]]=0;
            $newgoodAry[$tempAry[1]]=$newgoodAry[$tempAry[1]]+$tempAry[4];
            $temp=array($_W["uniacid"],$shopid,$orderid,$trade['out_trade_no'],TIMESTAMP,1,$tempAry[1],$tempAry[2],$tempAry[3],$tempAry[4],$tempAry[5],$tempAry[6],intval($tempAry[9]*100),0,$tempAry[8]);
            $tempInsertAry[]="('".implode("','",$temp)."')";
        }else{
            $isallnew=false;
            $temp=array(
                "price"=>$tempAry[5],
                "fee"=>intval($tempAry[9]*100),
//                "ispack"=>0,
                "taste"=>$tempAry[8]
            );
            //pdo_update("j_hmoney_ordergoods",$temp,array("id"=>$tempAry[0]));
        }
    }
    //--计算数量--//
    if(count($newgoodAry)){
        $goodataAry=array();
        $goodsql="UPDATE ".tablename('j_hmoney_goods')." SET store = CASE id ";
        $goodlist=pdo_fetchall("SELECT id,store,title FROM ".tablename('j_hmoney_goods')." WHERE id in (".implode(",",array_keys($newgoodAry)).") and store>-1 ");
        foreach($goodlist as $row){
            if($row['store']-$newgoodAry[$row['id']]<0){
                die($_GET['callback']."(".json_encode(array('success'=>false,'msg'=>"【".$row['title']."】库存不足,差【".abs($row['store']-$newgoodAry[$row['id']])."】份")).")");
                break;
            }
            $goodsql.=" WHEN ".$row['id']." THEN ". ($row['store']-$newgoodAry[$row['id']]);
        }
        $goodsql.="END WHERE id IN (".implode(",",array_keys($newgoodAry)).")";
        $sql=$sqlinsert.implode(",",$tempInsertAry).";".$goodsql;
        pdo_run($sql);
    }
    pdo_update("j_hmoney_table",array("status"=>2,"newctrl"=>1),array("id"=>$trade['tableid']));
    $gather=pdo_fetch("SELECT sum(num) as num1,count(*) as num2,sum(price*num*100) as tfee,sum(oldprice*num*100)as ofee FROM " . tablename('j_hmoney_ordergoods') . " WHERE weid = '".$_W['uniacid']."' and orderid=:a ",array(":a"=>$trade['id']));
    $gather2=pdo_fetch("SELECT sum(a.total_fee) as notfee FROM " . tablename('j_hmoney_ordergoods') . " a left join " . tablename('j_hmoney_goods') . " b on a.goodid=b.id WHERE a.weid = '".$_W['uniacid']."' and b.isnotcoupon=1 and a.out_trade_no=:a ",array(":a"=>$trade['out_trade_no']));
    $data=array(
        "order_fee"=>intval($gather['ofee']),
        "total_fee"=>intval($gather['tfee']),
        "notdiscount_fee"=>$gather2['notfee'],
        "num"=>$gather['num1'],
        "species"=>$gather['num2'],
        "status"=>1,
    );
    pdo_update("j_hmoney_order",$data,array("id"=>$orderid));
    //发送信息
    if(count($tempInsertAry)){
        $insertdata=array(
            "shopid"=>$shopid,
            "userid"=>$userid,
            "orderid"=>$orderid,
        );
        if($isallnew){
            $insertdata['mtype']="neworder";
            $insertdata['message']="[".date("m-d H:i")."][".$table['title']."]已下单，下单商品种类".count($newgoodAry)."，请及时处理。";
        }else{
            $insertdata['mtype']="addgood";
            $insertdata['message']="[".date("m-d H:i")."][".$table['title']."]加单，加单商品种类".count($newgoodAry)."，请及时处理。";
        }
        _sendWebMessage($insertdata);
        $this->wildDog_socket($shopid);
    }
    die($_GET['callback']."(".json_encode(array('success'=>true,"msg"=>"")).")");




} elseif ($operation == 'getgoodpackage') {
    $id=intval($_GPC['id']);
    $item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_goodpackage') . " WHERE id=:a", array(":a" => $id));
    $goodtemp=explode(",",$item['goodids']);
    $gids=array();
    $gprice=array();
    foreach($goodtemp as $row){
        $temp=explode(":",$row);
        $gids[]=$temp[0];
        $gprice[]=$temp[1];
    }
    $good1 = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_goods')." WHERE weid = '{$_W['uniacid']}' and id in (".implode(",",$gids).") order by id desc  ");
    $goodtemp1=array();
    foreach($good1 as $row){
        $goodtemp1[$row['id']]=$row;
    }
    $goodary=array();
    foreach($gids as $index=>$row){
        $goodary[$index]=$goodtemp1[$row];
        if($goodtemp1[$row]['thumb'])$goodary[$index]['thumb']=tomedia($goodtemp1[$row]['thumb']);
        $goodary[$index]['price']=$gprice[$index];
    }
    die($_GET['callback']."(".json_encode(array('success'=>true,'list'=>$goodary,"a"=>count($goodary))).")");

} elseif ($operation == 'getgood') {
    $id=intval($_GPC['id']);
    $item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_goods') . " WHERE id=:a", array(":a" => $id));
    die($_GET['callback']."(".json_encode(array('success'=>true,'item'=>$item)).")");

}elseif ($operation == 'getorderlist') {
    $date=$_GPC["date"];
    $starttime=strtotime($date." 00:00:00");
    $endtime=strtotime($date." 23:59:59");
    $orderlist=pdo_fetchall("SELECT a.*,b.title FROM ".tablename('j_hmoney_order')." a left join ".tablename('j_hmoney_table')." b  on a.tableid=b.id WHERE a.weid = '".$_W['uniacid']."' and a.groupid=:a and a.createtime>=:b and a.createtime<=:c order by a.id desc ",array(":a"=>$shopid,":b"=>$starttime,":c"=>$endtime));

    die($_GET['callback']."(".json_encode(array('success'=>true,'list'=>$orderlist,'a'=>$starttime)).")");

}elseif ($operation == 'gettradeview') {
    $orderid=$_GPC["orderid"];
    $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
    $table = pdo_fetch("SELECT * FROM ".tablename('j_hmoney_table')." WHERE id=:a ",array(":a"=>$trade["tableid"]));
    $goodlist=pdo_fetchall("SELECT a.*,b.title,b.memberprice,b.unitname,b.marketprice,b.pcate FROM ".tablename('j_hmoney_ordergoods')." as a LEFT JOIN ".tablename('j_hmoney_goods')." as b ON a.goodid=b.id  WHERE a.out_trade_no=:a order by a.id desc ",array(":a"=>$trade['out_trade_no']));

    die($_GET['callback']."(".json_encode(array('success'=>true,'table'=>$table,'trade'=>$trade,'goods'=>$goodlist,)).")");
}elseif($operation == 'searchgoods'){
    $keyword=$_GPC["keyword"];
    if(!$keyword)die($_GET['callback']."(".json_encode(array('success'=>true,'list'=>"")).")");
    $goodslist=pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goods') . " WHERE weid = '".$_W['uniacid']."' and groupid=:b and status=1 and store<>0 and (shorttitle like '%".$keyword."%' or title like '%".$keyword."%' or goodsn like '%".$keyword."%' ) order by displayorder asc,id asc",array(":b"=>$shopid));
    die($_GET['callback']."(".json_encode(array('success'=>true,'list'=>$goodslist,'keyword'=>$keyword)).")");

}elseif($operation == 'today'){
    //总营收：2000，优惠200，实际营收1800。总批数30批，批单150元，人均消费30元。

    $condition = " and groupid ='" . $shopid . "' and createdate='" . date("Y-m-d") . "' ";
    $items = pdo_fetch('SELECT COUNT(*) as num1,sum(order_fee) as fee1,sum(discount_fee) as fee2,sum(paid_fee) as fee3,sum(teafee) as fee4,sum(num) as num2 FROM ' . tablename('j_hmoney_order') . " WHERE weid='{$_W['uniacid']}' $condition  and ispay=1 ");
    /*充值部分*/
    $chargeitems = pdo_fetch('SELECT COUNT(*) as num1,sum(cash) as fee1 FROM ' . tablename('j_hmoney_recharge') . " WHERE weid='{$_W['uniacid']}' $condition  and status=1 and usetype=0 ");
    $refundorder = pdo_fetch('SELECT COUNT(*) as num1,sum(num) as num2,sum(fee) as fee1 FROM ' . tablename('j_hmoney_refund') . " WHERE weid='{$_W['uniacid']}' $condition  and status=1 and rtype=1 ");

    $condition2 = " and groupid ='" . $shopid . "' and createdate='" . date("Y-m-d",strtotime("-1 day")) . "' ";
    $items2 = pdo_fetch('SELECT COUNT(*) as num1,sum(order_fee) as fee1,sum(discount_fee) as fee2,sum(paid_fee) as fee3,sum(teafee) as fee4,sum(num) as num2 FROM ' . tablename('j_hmoney_order') . " WHERE weid='{$_W['uniacid']}' $condition2  and ispay=1 ");

    $chargeitems2 = pdo_fetch('SELECT COUNT(*) as num1,sum(cash) as fee1 FROM ' . tablename('j_hmoney_recharge') . " WHERE weid='{$_W['uniacid']}' $condition2 and status=1 and usetype=0 ");

    $today=array(
        "fee1"=>$items['fee3'],
        "num1"=>$items['num1'],
        "fee2"=>$chargeitems['fee1'],
    );
    $yestoday=array(
        "fee1"=>$items2['fee3'],
        "num1"=>$items2['num1'],
        "fee2"=>$chargeitems2['fee1'],
    );
    die($_GET['callback']."(".json_encode(array('success'=>true,'today'=>$items,'yestoday'=>$yestoday)).")");


}elseif($operation == 'checkupdate') {
    $appversion = $_GPC["appversion"];
    $appversion = str_replace(".", "", $appversion);
    $isseting = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_systemsetting') . " order by id asc limit 1");
    if (!$isseting["appurl"]) die($_GET['callback'] . "(" . json_encode(array('success' => false, 'msg' => "暂无更新1" . $isseting["appurl"])) . ")");
    load()->func('file');
    $dir_url = "/attachment/j_hmoney/cert_2/";
    $fileurl = $_W['siteroot'] . "/attachment/j_hmoney/cert_2/" . $isseting["appurl"];
    die($_GET['callback'] . "(" . json_encode(array('success' => true, 'fileurl' => $fileurl)) . ")");

//以下为轻餐饮内容
}elseif ($operation == 'l_getorderdietal') {
    $orderid=intval($_GPC['orderid']);
    if(!$orderid){
        $orderDisplayorder=pdo_fetchcolumn("SELECT max(CONVERT(serialnum,SIGNED))  FROM " . tablename('j_hmoney_order') . " WHERE weid=:c and groupid=:a and createdate=:b ",array(":a"=>$shopid,":b"=>date("Y-m-d"),":c"=>$_W['uniacid']));
        $orderDisplayorder=$orderDisplayorder+1;
        if(strlen($orderDisplayorder)<4){
            $temp="";
            for($i=0;$i<4-strlen($orderDisplayorder);$i++){
                $temp.="0";
            }
            $orderDisplayorder=$temp.$orderDisplayorder;
        }
        $data=array(
            "weid"=>$_W['uniacid'],
            "groupid"=>$shopid,
            "userid"=>$userid,
            "serialnum"=>$orderDisplayorder,
            "out_trade_no"=>TIMESTAMP.mt_rand(100,999),
            "createtime"=>TIMESTAMP,
            "createdate"=>date("Y-m-d"),
            "createterminal"=>1,
        );
        pdo_insert("j_hmoney_order",$data);
        $orderid=pdo_insertid();
        $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
        die($_GET['callback']."(".json_encode(array('success'=>true,'trade'=>$trade)).")");
    }else{
        $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
        $goodlist=pdo_fetchall("SELECT a.*,b.title,b.memberprice,b.unitname,b.marketprice,b.pcate FROM ".tablename('j_hmoney_ordergoods')." as a LEFT JOIN ".tablename('j_hmoney_goods')." as b ON a.goodid=b.id  WHERE a.out_trade_no=:a order by a.id desc ",array(":a"=>$trade['out_trade_no']));
        die($_GET['callback']."(".json_encode(array('success'=>true,'trade'=>$trade,'goods'=>$goodlist)).")");
    }
    die($_GET['callback']."(".json_encode(array("success"=>true)).")");

}elseif ($operation == 'l_getback') {
    $list=pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_order') . " WHERE weid=:c and groupid=:a and createdate=:b  and ispay=0 order by id desc",array(":a"=>$shopid,":b"=>date("Y-m-d"),":c"=>$_W['uniacid']));

    die($_GET['callback']."(".json_encode(array('success'=>true,'list'=>$list)).")");

}elseif ($operation == 'l_updateordergoods') {
    $orderid=$_GPC["orderid"];
    $param=$_GPC["orderary"];
    $ishold=intval($_GPC["ishold"]);
    if(!$orderid)die($_GET['callback']."(".json_encode(array('success'=>false,'msg'=>"订单编号不能为空")).")");
    $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
    if($trade["ispay"])die($_GET['callback']."(".json_encode(array('success'=>false,'msg'=>"订单已付款")).")");
    $sqlinsert="insert into ".tablename('j_hmoney_ordergoods')." (weid,groupid,orderid,out_trade_no,createtime,status,goodid,title,goodsn,num,price,oldprice,total_fee,ispack,taste)VALUES";
    $newgoodAry=array();
    $tempInsertAry=array();
    $isallnew=true;
    $param=explode("|**|",$param);
    foreach($param as $row){
        //oid + "|*|" + gid + "|*|" + title + "|*|" + goodsn + "|*|" + num + "|*|" + price + "|*|" + oprice + "|*|" + mprice + "|*|" + taste + "|*|" + fee
        $tempAry=explode("|*|",$row);
        if(!$tempAry[0]){
            if(!isset($newgoodAry[$tempAry[1]]))$newgoodAry[$tempAry[1]]=0;
            $newgoodAry[$tempAry[1]]=$newgoodAry[$tempAry[1]]+$tempAry[4];
            $temp=array($_W["uniacid"],$shopid,$orderid,$trade['out_trade_no'],TIMESTAMP,1,$tempAry[1],$tempAry[2],$tempAry[3],$tempAry[4],$tempAry[5],$tempAry[6],intval($tempAry[9]*100),0,$tempAry[8]);
            $tempInsertAry[]="('".implode("','",$temp)."')";
        }else{
            $isallnew=false;
            $temp=array(
                "price"=>$tempAry[5],
                "fee"=>intval($tempAry[9]*100),
                "taste"=>$tempAry[8]
            );
            pdo_update("j_hmoney_ordergoods",$temp,array("id"=>$tempAry[0],"isprint"=>0));
        }
    }
    //--计算数量--//
    if(count($newgoodAry)){
        $goodataAry=array();
        $goodsql="UPDATE ".tablename('j_hmoney_goods')." SET store = CASE id ";
        $goodlist=pdo_fetchall("SELECT id,store,title FROM ".tablename('j_hmoney_goods')." WHERE id in (".implode(",",array_keys($newgoodAry)).") and store>-1 ");
        foreach($goodlist as $row){
            if($row['store']-$newgoodAry[$row['id']]<0){
                die($_GET['callback']."(".json_encode(array('success'=>false,'msg'=>"【".$row['title']."】库存不足,差【".abs($row['store']-$newgoodAry[$row['id']])."】份")).")");
                break;
            }
            $goodsql.=" WHEN ".$row['id']." THEN ". ($row['store']-$newgoodAry[$row['id']]);
        }
        $goodsql.="END WHERE id IN (".implode(",",array_keys($newgoodAry)).")";
        $sql=$sqlinsert.implode(",",$tempInsertAry).";".$goodsql;
        pdo_run($sql);
    }
    $gather=pdo_fetch("SELECT sum(num) as num1,count(*) as num2,sum(price*num*100) as tfee,sum(oldprice*num*100)as ofee FROM " . tablename('j_hmoney_ordergoods') . " WHERE weid = '".$_W['uniacid']."' and orderid=:a ",array(":a"=>$trade['id']));
    $gather2=pdo_fetch("SELECT sum(a.total_fee) as notfee FROM " . tablename('j_hmoney_ordergoods') . " a left join " . tablename('j_hmoney_goods') . " b on a.goodid=b.id WHERE a.weid = '".$_W['uniacid']."' and b.isnotcoupon=1 and a.out_trade_no=:a ",array(":a"=>$trade['out_trade_no']));
    $data=array(
        "order_fee"=>intval($gather['ofee']),
        "total_fee"=>intval($gather['tfee']),
        "notdiscount_fee"=>$gather2['notfee'],
        "num"=>$gather['num1'],
        "species"=>$gather['num2'],
        "status"=>!$ishold ? 1 : 0,
    );
    pdo_update("j_hmoney_order",$data,array("id"=>$orderid));
    die($_GET['callback']."(".json_encode(array('success'=>true,"msg"=>"")).")");

}elseif ($operation == 'print') {
    $orderid=$_GPC["orderid"];
    $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
    if(!$trade["ispay"])die($_GET['callback']."(".json_encode(array('success'=>false,'msg'=>"订单没有付款，不能打印")).")");
    /*传输打印接口*/
    $insertdata=array(
        "shopid"=>$shopid,
        "userid"=>$userid,
        "orderid"=>$orderid,
    );
    $insertdata['mtype']="printnew";
    $insertdata['message']="[".date("m-d H:i")."][".$trade['serialnum']."]，请求厨房打印。";
    _sendWebMessage($insertdata);
    /**/
    die($_GET['callback']."(".json_encode(array('success'=>true)).")");
}

